﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using log4net;

public partial class Index : System.Web.UI.Page
{
    
    protected string environment;
    protected string csrfToken;

    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected void Page_Load(object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();

        //setting the environment for Checkout script
        bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));

        if (sandboxFlag)
        {
            this.environment = System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_ENV");
        }
        else
        {
            this.environment = System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_ENV");
        }

        // Synchronizer (CSRF) Token for Cross-Site Request Forgery defense
        csrfToken = PayPalMethods.getCsrfToken();
        Session["csrf"] = csrfToken;

        log.Info(
            "Sandbox Environment: " + sandboxFlag.ToString() + Environment.NewLine +
            "CSRF Token : " + csrfToken
        );

        var hostName = Request.ServerVariables["HTTP_HOST"];
        var appName = String.IsNullOrEmpty(Request.ServerVariables["REQUEST_URI"].Split('/')[0]) ? "" : Request.ServerVariables["REQUEST_URI"].Split('/')[0] + "/";

        var cancelUrl = "http://" + hostName + "/" + appName + "Cancel.aspx";
        var payUrl = "http://" + hostName + "/" + appName + "Pay.aspx";
        var placeOrderUrl = "http://" + hostName + "/" + appName + "PlaceOrder.aspx";

        // JSON data for REST API calls.

        // Session["expressCheckoutPaymentData"] is used in the PayPal Check Out flow
        PayPalObjects.ExpressCheckoutPaymentData expressCheckoutPaymentData = new PayPalObjects.ExpressCheckoutPaymentData(cancelUrl, placeOrderUrl);
        string expressCheckoutPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutPaymentData, Formatting.Indented);
        Session["expressCheckoutPaymentData"] = expressCheckoutPaymentDataJson;

        // Session["expressCheckoutShippingPaymentData"] is used for the Proceed to Checkout flow
        PayPalObjects.ExpressCheckoutShippingPaymentData expressCheckoutShippingPaymentData = new PayPalObjects.ExpressCheckoutShippingPaymentData(cancelUrl, payUrl);
        string expressCheckoutShippingPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutShippingPaymentData, Formatting.Indented);
        Session["expressCheckoutShippingPaymentData"] = expressCheckoutShippingPaymentDataJson;
    }

}
